package com.bsj.power.job.config.async;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author yinhao
 * @version 1.0
 * @description 异步线程池
 * @date 2024/4/18
 */
@Configuration
public class AsyncConfig {

    /**
     * 核心线程数（默认线程数）
     */
    @Value("${threadBus.pool.core-pool-size}")
    private int corePoolSize = Runtime.getRuntime().availableProcessors();
    /**
     * 最大线程数
     */
    @Value("${threadBus.pool.max-pool-size}")
    private int maxPoolSize = Runtime.getRuntime().availableProcessors();
    /**
     * 允许线程空闲时间（单位：默认为秒）
     */
    @Value("${threadBus.pool.keep-alive-time}")
    private int keepAliveTime = 60;
    /**
     * 缓冲队列大小
     */
    @Value("${threadBus.pool.queue-capacity}")
    private int queueCapacity = 200;
    /**
     * 线程池名前缀
     */
    @Value("${threadBus.pool.thread-name-prefix}")
    private String threadNamePrefix = "PowerModuleJobAsync-";

    /**
     * 全局共享线程池配置
     * @return
     */
    @Bean(name = "powerJobAsync")
    public Executor powerJobAsync() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //设置核心线程数
        taskExecutor.setCorePoolSize(corePoolSize);
        // 线程池维护线程的最大数量，只有在缓冲队列满了以后才会申请超过核心线程数的线程
        taskExecutor.setMaxPoolSize(maxPoolSize);
        //缓存队列
        taskExecutor.setQueueCapacity(queueCapacity);
        //允许的空闲时间，当超过了核心线程数之外的线程在空闲时间到达之后会被销毁
        taskExecutor.setKeepAliveSeconds(keepAliveTime);
        //异步方法内部线程名称
        taskExecutor.setThreadNamePrefix(threadNamePrefix + "powerJobAsync-");
        //拒绝策略
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.setAwaitTerminationSeconds(keepAliveTime);
        taskExecutor.initialize();
        return taskExecutor;
    }
}
